package com.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lease.common.exception.LeaseException;
import com.lease.common.result.ResultCodeEnum;
import com.lease.model.entity.*;
import com.lease.model.enums.ItemType;
import com.lease.web.admin.mapper.*;
import com.lease.web.admin.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.lease.web.admin.vo.fee.FeeValueVo;
import com.lease.web.admin.vo.graph.GraphVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

import static org.bouncycastle.asn1.x500.style.RFC4519Style.o;

/**
 *
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private GraphInfoService graphInfoService;

    @Autowired
    private  ProvinceInfoService provinceInfoService;
    @Autowired
    private  CityInfoService cityInfoService;
    @Autowired
    private  DistrictInfoService districtInfoService;

    @Autowired
    private  ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    private LeaseAgreementMapper leaseAgreementMapper;
    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private FeeValueMapper feeValueMapper;
    @Autowired
    private GraphInfoMapper graphInfoMapper;
    @Autowired
    private  LabelInfoMapper labelInfoMapper;
    @Autowired
    private  RoomInfoMapper roomInfoMapper;
    @Override
    public void saveOrUpdateApartment(ApartmentSubmitVo apartmentSubmitVo) {
          //根据vo对象的id是否为空判断是否是更新还是新增
           boolean isUpdate  = apartmentSubmitVo.getId() != null;

           if (isUpdate) {
               //先删除公寓的等的中间表
               apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>().eq(ApartmentFacility::getApartmentId, apartmentSubmitVo.getId()));
               apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId, apartmentSubmitVo.getId()));
               apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId, apartmentSubmitVo.getId()));
               graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemType, ItemType.APARTMENT).eq(GraphInfo::getItemId, apartmentSubmitVo.getId()));
               apartmentInfoMapper.delete(new LambdaQueryWrapper<ApartmentInfo>().eq(ApartmentInfo::getId,apartmentSubmitVo.getId()));

           }

           //新增公寓
          //公寓信息表
          ApartmentInfo apartmentInfo = new ApartmentInfo();
           BeanUtils.copyProperties(apartmentSubmitVo, apartmentInfo);
           apartmentInfo.setProvinceName(provinceInfoService.getById(apartmentSubmitVo.getProvinceId()).getName());
           apartmentInfo.setCityName(cityInfoService.getById(apartmentSubmitVo.getCityId()).getName());
           apartmentInfo.setDistrictName(districtInfoService.getById(apartmentSubmitVo.getDistrictId()).getName());
          apartmentInfoMapper.insert(apartmentInfo);
          // 公寓-配套设施表
          List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
          if (!CollectionUtils.isEmpty(facilityInfoIds)) {
              List<ApartmentFacility> apartmentFacilityList = facilityInfoIds.stream()
                  .map(facilityId -> {
                      ApartmentFacility apartmentFacility = new ApartmentFacility();
                      apartmentFacility.setApartmentId(apartmentInfo.getId());
                      apartmentFacility.setFacilityId(facilityId);
                      return apartmentFacility;
                  })
                  .toList();
              apartmentFacilityService.saveBatch(apartmentFacilityList);
          }

          // 公寓-标签表
          List<Long> labelIds = apartmentSubmitVo.getLabelIds();
          if (!CollectionUtils.isEmpty(labelIds)) {
              List<ApartmentLabel> apartmentLabelList = labelIds.stream()
                  .map(labelId -> {
                      ApartmentLabel apartmentLabel = new ApartmentLabel();
                      apartmentLabel.setApartmentId(apartmentInfo.getId());
                      apartmentLabel.setLabelId(labelId);
                      return apartmentLabel;
                  })
                  .toList();
              apartmentLabelService.saveBatch(apartmentLabelList);
          }

          // 公寓-杂费值表
          List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
          if (!CollectionUtils.isEmpty(feeValueIds)) {
              List<ApartmentFeeValue> apartmentFeeValueList = feeValueIds.stream()
                  .map(feeValueId -> {
                      ApartmentFeeValue apartmentFeeValue = new ApartmentFeeValue();
                      apartmentFeeValue.setApartmentId(apartmentInfo.getId());
                      apartmentFeeValue.setFeeValueId(feeValueId);
                      return apartmentFeeValue;
                  })
                  .toList();
              apartmentFeeValueService.saveBatch(apartmentFeeValueList);
          }


          //公寓-图片表
         apartmentSubmitVo.getGraphVoList().forEach(graphVo -> {
            GraphInfo graphInfo = new GraphInfo();
            BeanUtils.copyProperties(graphVo, graphInfo);
            graphInfo.setItemId(apartmentInfo.getId());
            graphInfo.setItemType(ItemType.APARTMENT);
            graphInfoMapper.insert(graphInfo);
        });



    }






    @Override
    public ApartmentDetailVo getApartmentDetailById(Long id) {
        //1.查询ApartmentInfo
        ApartmentInfo apartmentInfo = this.getById(id);
        if (apartmentInfo == null) {
            return null;
        }

        //2.查询GraphInfo
        List<GraphVo> graphVoList = graphInfoMapper.selectListByItemTypeAndId(ItemType.APARTMENT, id);

        //3.查询LabelInfo
        List<LabelInfo> labelInfoList = labelInfoMapper.selectListByApartmentId(id);

        //4.查询FacilityInfo
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.selectListByApartmentId(id);

        //5.查询FeeValue
        List<FeeValueVo> feeValueVoList = feeValueMapper.selectListByApartmentId(id);

        ApartmentDetailVo adminApartmentDetailVo = new ApartmentDetailVo();

        BeanUtils.copyProperties(apartmentInfo, adminApartmentDetailVo);
        adminApartmentDetailVo.setGraphVoList(graphVoList);
        adminApartmentDetailVo.setLabelInfoList(labelInfoList);
        adminApartmentDetailVo.setFacilityInfoList(facilityInfoList);
        adminApartmentDetailVo.setFeeValueVoList(feeValueVoList);

        return adminApartmentDetailVo;
    }

    @Override
    public void removeApartmentById(Long id) {
        LambdaQueryWrapper<RoomInfo> roomQueryWrapper = new LambdaQueryWrapper<>();
        roomQueryWrapper.eq(RoomInfo::getApartmentId, id);
        Long count = roomInfoMapper.selectCount(roomQueryWrapper);
        if (count > 0) {
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
            //直接为前端返回如下响应：先删除房间信息再删除公寓信息
        }

        //1.删除GraphInfo
        LambdaQueryWrapper<GraphInfo> graphQueryWrapper = new LambdaQueryWrapper<>();
        graphQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
        graphQueryWrapper.eq(GraphInfo::getItemId, id);
        graphInfoService.remove(graphQueryWrapper);

        //2.删除ApartmentLabel
        LambdaQueryWrapper<ApartmentLabel> labelQueryWrapper = new LambdaQueryWrapper<>();
        labelQueryWrapper.eq(ApartmentLabel::getApartmentId, id);
        apartmentLabelService.remove(labelQueryWrapper);

        //3.删除ApartmentFacility
        LambdaQueryWrapper<ApartmentFacility> facilityQueryWrapper = new LambdaQueryWrapper<>();
        facilityQueryWrapper.eq(ApartmentFacility::getApartmentId, id);
        apartmentFacilityService.remove(facilityQueryWrapper);

        //4.删除ApartmentFeeValue
        LambdaQueryWrapper<ApartmentFeeValue> feeQueryWrapper = new LambdaQueryWrapper<>();
        feeQueryWrapper.eq(ApartmentFeeValue::getApartmentId, id);
        apartmentFeeValueService.remove(feeQueryWrapper);

         this.removeById(id);

    }

    @Override
    public IPage<ApartmentItemVo> pageApartmentItemByQuery(Page<ApartmentItemVo> apartmentItemVoPage, ApartmentQueryVo queryVo) {
        return apartmentInfoMapper.pageApartmentItemByQuery(apartmentItemVoPage, queryVo);

    }

}




